<template>
  <div class="system-info">
    <div class="main-middle">
      <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
              <!-- 流程编号 -->
              <el-form-item label="流程编号">
                <el-input v-model.trim="formInline.flowCode" clearable></el-input>
                <!-- <el-select
                  v-model="formInline.flowCode"
                  filterable
                  auto-complete="off"
                  placeholder="请选择"
                  style="width:150px;"
                >
                  <el-option label="无" value></el-option>
                  <el-option
                    v-for="(item,index) in flowList"
                    :key="index"
                    :label="item.flowName"
                    :value="item.flowId"
                  ></el-option>
              </el-select> -->
            </el-form-item>
            <!-- 申请日期 -->
            <el-form-item label="申请日期">
              <el-date-picker v-model="formInline.flowOriginatorTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <!-- <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1"> -->
          <!-- 发起流程 -->
          <!-- <el-button
            v-if="btnAdd"
            type="success"
            size="medium"
            icon="el-icon-document-add"
            @click="drawer = true"
          >发起流程</el-button>
        </el-row> -->
        <!-- 数据列表 -->
        <el-table
          :data="menusData"
          border
          style="width: 100%"
          height="580"
          ref="menusData"
        >
          <!-- 流程名称 -->
          <el-table-column :show-overflow-tooltip="true" prop="flowCode" label="流程编号" width="250"></el-table-column>
          <!-- 当前环节 -->
          <el-table-column label="当前环节" align="center" width="200">
            <template slot-scope="scope">{{ scope.row.flowCurrentNode | getNode(scope.row) }}</template>
          </el-table-column>
          <!-- 审批人 -->
          <el-table-column label="审批人" align="center">
            <template slot-scope="scope">{{ scope.row.flowCurrentUser | getName(users) }}</template>
          </el-table-column>
          <!-- 工单状态 -->
          <el-table-column align="center" label="状态" width="200">
            <template slot-scope="scope">
              <!-- 工单状态 1.暂存草稿 2.已发起 3.正常处理 4.处理完成 5.驳回申请 -->
              <span v-if="scope.row.status === 1">
                暂存草稿
              </span>
              <span v-if="scope.row.status === 2">
                已发起
              </span>
              <span v-if="scope.row.status === 3">
                正常处理
              </span>
              <span v-if="scope.row.status === 4">
                处理完成
              </span>
              <span v-if="scope.row.status === 5">
                驳回申请
              </span>
            </template>
          </el-table-column>
          <!-- 申请日期 时间格式过滤 -->
          <el-table-column label="申请日期" align="center" width="200">
            <template slot-scope="scope">{{ scope.row.createTime | filterTime }}</template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column
            label="管理"
            fixed="right"
            align="center"
            width="150"
            v-if="[btnDel,btnEdit].indexOf(true) > -1"
          >
            <template slot-scope="scope">
              <el-dropdown>
                <el-button type="primary" size="mini">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu>
                  <el-dropdown-item><el-button type="success" size="mini" @click="initiate(scope.row)" v-if="scope.row.status === 1">立即申请</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button type="warning" size="mini" @click="reapply(scope.row)" v-if="scope.row.status === 5">重新申请</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button type="primary" size="mini" @click="editHandle(scope.row)" v-if="scope.row.status === 1 || scope.row.status === 5">修改编辑</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button type="danger" size="mini" @click="deleteLc(scope.row)" v-if="scope.row.status === 1">删除流程</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button size="mini" @click="formDatas(scope.row)" v-if="scope.row.status !== 1">表单数据</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button type="info" size="mini" @click="history(scope.row)" v-if="scope.row.status !== 1">审批历史</el-button></el-dropdown-item>
                  <el-dropdown-item><el-button type="danger" size="mini" @click="cancel(scope.row)" v-if="scope.row.status !== 1 && scope.row.status !== 4">取消申请</el-button></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- 立即申请 -->
              <!-- <el-button
                type="success"
                size="mini"
                @click="initiate(scope.row)"
                v-if="scope.row.status === 1"
              >立即申请</el-button> -->
              <!-- 重新申请 -->
              <!-- <el-button
                type="warning"
                size="mini"
                @click="reapply(scope.row)"
                v-if="scope.row.status === 5"
              >重新申请</el-button> -->
              <!-- 修改编辑 -->
              <!-- <el-button
                type="primary"
                size="mini"
                @click="editHandle(scope.row)"
                v-if="scope.row.status === 1 || scope.row.status === 5"
              >修改编辑</el-button> -->
              <!-- 立即申请 -->
              <!-- <el-button
                type="danger"
                size="mini"
                @click="deleteLc(scope.row)"
                v-if="scope.row.status === 1"
              >删除流程</el-button> -->
              <!-- 表单数据 -->
              <!-- <el-button size="mini" @click="formDatas(scope.row)" v-if="scope.row.status !== 1">表单数据</el-button> -->
              <!-- 审批历史 -->
              <!-- <el-button type="info" size="mini" @click="history(scope.row)" v-if="scope.row.status !== 1">审批历史</el-button> -->
              <!-- 取消申请 -->
              <!-- <el-button
                type="danger"
                size="mini"
                @click="cancel(scope.row)"
                v-if="scope.row.status !== 1 && scope.row.status !== 4"
              >取消申请</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      <el-drawer
        title="选择流程"
        :visible.sync="drawer"
        close-on-press-escape
        :with-header="false">
        <flow-list @cls="getCls"></flow-list>
      </el-drawer>
      <el-dialog title="流程图" :visible.sync="modalVisible" width="600px">
        <div class="flowLog">
          <el-table
            :data="historyLog"
            border
            style="width: 100%">
            <!-- 处理人 -->
            <el-table-column label="处理人" align="center" width="100">
              <template slot-scope="scope">{{ scope.row.createUserId | getName(users) }}</template>
            </el-table-column>
            <!-- 处理日期 时间格式过滤 -->
            <el-table-column label="处理日期" align="center" width="120">
              <template slot-scope="scope">{{ scope.row.createTime | filterTime }}</template>
            </el-table-column>
            <el-table-column align="center" label="结果" width="60">
              <template slot-scope="scope">
                <!-- 处理结果 1.发起 2.通过 3.驳回 4.取消 -->
                <span v-if="scope.row.result === 1">
                  发起
                </span>
                <span v-if="scope.row.result === 2">
                  通过
                </span>
                <span v-if="scope.row.result === 3">
                  驳回
                </span>
                <span v-if="scope.row.result === 4">
                  取消
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="note"
              label="审批说明">
            </el-table-column>
          </el-table>
        </div>
        <node-data ref="nodeFlow" :nodeData="nodeData"></node-data>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';
// 节点展示组件
import NodeData from '@/components/NodeData';
// 引入流程列表组件
import flowList from '@/components/FlowList';

export default {
  components: {
    flowList,
    NodeData
  },
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    },
    'flowType': String,
    'tabCode': String
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    },

    // 监听流程类型
    flowType: {
      immediate: true,
      handler (newVal, oldVal) {
        this.flowType = newVal;
      }
    },

    // 监听tab类型
    tabCode: {
      immediate: true,
      handler (newVal, oldVal) {
        if (newVal === 'first') {
          // 加载分页数据
          this.getmenusDataByPage();
          // 获取所有流程模型数据
          this.getFlowList();

          // 获取所有用户数据
          this.getAllUsers();
        }
      }
    }
  },

  // 实例创建后执行
  async created () {
    // 按钮级授权
    await this.authorization(this.$store.state.btns);
    // 查出当前申请人所在部门角色池领导
    this.getRoleList();
  },

  // 过滤器
  filters: {
    // 时间显示过滤
    filterTime (value) {
      return moment(value).format('YYYY-MM-DD') === 'Invalid date' ? '无' : moment(value).format('YYYY-MM-DD');
    },
    // 节点过滤
    getNode (value, datas) {
      if (datas.flowJson !== undefined) {
        let lists = JSON.parse(datas.flowJson);
        for (let i = 0; i < lists.nodes.length; i++) {
          if (lists.nodes[i].id === value) {
            return lists.nodes[i].label;
          }
        }
      }
    },
    // 审批人过滤
    getName (value, params) {
      if (value && value.indexOf(',') > -1) {
        let userNameList = [];
        let valueList = value.split(',');
        for (let i = 0; i < params.length; i++) {
          for (let j = 0; j < valueList.length; j++) {
            if (params[i].userId === valueList[j]) {
              userNameList.push(params[i].userName);
            }
          }
        }
        return userNameList.join(',');
      } else {
        for (let i = 0; i < params.length; i++) {
          if (params[i].userId === value) {
            return params[i].userName;
          }
        }
      }
    }
  },

  // 当前页面数据
  data () {
    return {
      // 项目经理
      proMsgId: [],
      // 流程菜单是否显示
      drawer: false,
      // 屏蔽重复提交
      isSubmit: false,
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 获取公司列表
      lv1: [],
      // 获取部门列表
      lv2: [],

      // 过滤器匹配
      dept: [],

      // 当前用户数据
      users: '',

      // 搜索条件
      formInline: {
        // 流程模型ID
        flowCode: '',
        // 工单申请时间
        flowOriginatorTime: ''
      },

      // 流程图预览数据
      nodeData: {},
      // 流程历史是否显示
      modalVisible: false,
      // 所有流程信息
      flowList: [],
      // 审批历史数据
      historyLog: [],
      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,
      // 节点压缩后的审批节点，审批人
      globalParams: {
        globalFlowCurrentNode: '',
        globallowCurrentUser: ''
      }
    };
  },

  mounted () {
    // this.getHeight();
    // 增加监听事件，窗口变化时得到高度。
    // window.addEventListener('resize', this.getHeight, false);
  },
  methods: {
    // 表格高度自适应
    // getHeight () {
    // // 获取浏览器高度并计算得到表格所用高度。
    //   this.tableHeight = document.documentElement.clientHeight - 350;
    // },
    // 获取所有用户
    getAllUsers () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.users = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有流程数据
    getFlowList: function () {
      this.$http.raw('api/findAllFlow').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.flowList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取流程模型组件数据
    getCls (data) {
      this.drawer = data;
    },

    // 按钮级授权
    authorization (data) {
      for (let i in data) {
        if (data['sel'] === 0) {
          this.btnSel = false;
          return this.btnSel;
        }
        if (data['add'] === 0) {
          this.btnAdd = false;
          return this.btnAdd;
        }
        if (data['del'] === 0) {
          this.btnDel = false;
          return this.btnDel;
        }
        if (data['upload'] === 0) {
          this.btnUpload = false;
          return this.btnUpload;
        }
        if (data['down'] === 0) {
          this.btnDown = false;
          return this.btnDown;
        }
        if (data['edit'] === 0) {
          this.btnEdit = false;
          return this.btnEdit;
        }
        return i;
      }
    },

    // 创建项目存入表中
    initiate (row) {
      let _this = this;
      if (row.flowId.indexOf('LXSQ') === -1) {
        _this.createPro(row);
      } else {
        let rowDB = JSON.parse(row.formJson);
        let userId = rowDB.pmp;
        if (userId.indexOf('[') && userId.indexOf(']')) {
          userId = userId.slice(userId.indexOf('[') + 1, userId.indexOf(']'));
        }
        // 收集请求数据
        let params = {
          // 标记转签
          sign: rowDB.sign,
          // 接收转签
          receive: rowDB.receive,
          // 关联项目
          related: rowDB.related,
          // 关联公司
          compId: rowDB.compId,
          // 关联公司名称
          // compName: '浩方信息',
          // 项目类型
          type: rowDB.type,
          // 关联客户
          cusId: rowDB.cusId,
          // 归属部门ID
          deptId: rowDB.deptId,
          // 客户部门
          cusDeptCode: rowDB.cusDeptCode.split('-')[0],
          // 客户部门--回显
          cusDeptName: rowDB.cusDeptCode.split('-')[1],
          // 项目合同编号
          contractCode: rowDB.contractCode,
          // 项目名称
          proName: rowDB.proName,
          // 项目经理
          pmp: userId,
          // 项目周期 - 开始时间
          cycleStart: rowDB.cycleEnd,
          // 项目周期 - 结束时间
          cycleEnd: rowDB.cycleStart,
          // 费用类型
          costType: rowDB.costType,
          // 预算金额
          amount: rowDB.amount,
          // 费用周期 - 开始时间
          costCycleStart: rowDB.costCycle ? rowDB.costCycle[0] : '',
          // 费用周期 - 结束时间
          costCycleEnd: rowDB.costCycle ? rowDB.costCycle[1] : '',
          // 备注说明
          note: rowDB.msg,
          // 是否有效
          mark: 0
        };

        this.$http.raw('api/insertPro', params).then(res => {
          let { code, datas } = res;
          // 判断Code状态
          if (code === 0) {
            _this.createPro(row, datas);
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }
    },
    // 发起申请
    async createPro (row, proId) {
      let _this = this;
      let userId = _this.$store.state.userinfo.userId;
      // 当前所处节点
      let prevNode = row.flowCurrentNode;
      let msgList = JSON.parse(row.formJson).msgList;
      if ((msgList.length && msgList.indexOf(userId) > -1) || (msgList.length === 0)) {
        await _this.getNextNode(row, prevNode, 2);
      } else {
        await _this.getNextNode(row, prevNode, 1);
      }
      // 当前流程模型编号
      // let flowId = row.flowId;
      setTimeout(() => {
        let params = {
          // 工单编号
          flowCode: row.flowCode,
          flowOriginator: _this.$store.state.userinfo.userId,

          flowCurrentNode: _this.globalParams.globalFlowCurrentNode,
          flowCurrentUser: _this.globalParams.globallowCurrentUser,
          // 工单优先级
          // flowPriority: row.flowPriority,
          // 消息推送
          // msgPush: row.msgPush,
          flowNode: row.flowCurrentNode,
          status: 2,
          result: '已发起',
          note: '发起申请',
          workResult: 1
        };
        _this.$http.raw('api/updateOrderStatus', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            _this.$message({
              message: '发起流程成功！',
              type: 'success'
            });
            _this.getmenusDataByPage();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }, 500);
    },

    // 重新申请
    async reapply (row, proId) {
      let _this = this;
      // 当前所处节点
      let prevNode = row.flowCurrentNode;
      let userId = _this.$store.state.userinfo.userId;
      let msgList = JSON.parse(row.formJson).msgList;
      if ((msgList.length && msgList.indexOf(userId) > -1) || (msgList.length === 0)) {
        await _this.getNextNode(row, prevNode, 2);
      } else {
        await _this.getNextNode(row, prevNode, 1);
      }

      setTimeout(() => {
        let params = {
          // 工单编号
          flowCode: row.flowCode,
          flowOriginator: _this.$store.state.userinfo.userId,

          flowCurrentNode: _this.globalParams.globalFlowCurrentNode,
          flowCurrentUser: _this.globalParams.globallowCurrentUser,
          // 工单优先级
          // flowPriority: row.flowPriority,
          // 消息推送
          // msgPush: row.msgPush,
          flowNode: row.flowCurrentNode,
          status: 2,
          result: '已发起',
          note: '发起申请',
          workResult: 1
        };
        _this.$http.raw('api/updateOrderStatus', params).then(res => {
          let { code } = res;
          // 判断Code状态
          if (code === 0) {
            _this.$message({
              message: '发起流程成功！',
              type: 'success'
            });
            _this.getmenusDataByPage();
          }
        }).catch(err => {
          if (err === undefined) {
            _this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }, 500);
      // 当前流程模型编号
      // let flowId = row.flowId;
      // // 公司
      // let compId = JSON.parse(row.formJson).compDeptUser.code[0];
      // // 部门
      // let deptId = JSON.parse(row.formJson).compDeptUser.code[1];

      // // 立即申请判断当前节点的下一步审批节点
      // let params = {
      //   prevNode,
      //   flowId
      // };
      // _this.$http.post('/api/findNextNode', params).then(res => {
      //   let {code, datas} = res;
      //   if (code === 0) {
      //     let nextNode = datas.flowNodeId;
      //     let role = datas.flowNodeRole;
      //     let user = datas.note;

      //     // 判断是否存在审批角色池
      //     if (role !== '') {
      //       if (role === '发起人') {
      //         let params = {
      //           // 工单编号
      //           flowCode: row.flowCode,
      //           flowOriginator: _this.$store.state.userinfo.userId,

      //           flowCurrentNode: nextNode,
      //           flowCurrentUser: _this.$store.state.userinfo.userId,
      //           // 工单优先级
      //           flowPriority: row.flowPriority,
      //           // 消息推送
      //           msgPush: row.msgPush,
      //           flowNode: row.flowCurrentNode,
      //           status: 2,
      //           result: '已发起',
      //           note: '发起申请',
      //           workResult: 1
      //         };
      //         _this.$http.raw('api/updateOrderStatus', params).then(res => {
      //           let { code } = res;
      //           // 判断Code状态
      //           if (code === 0) {
      //             _this.$message({
      //               message: '发起流程成功！',
      //               type: 'success'
      //             });
      //             _this.getmenusDataByPage();
      //           }
      //         }).catch(err => {
      //           if (err === undefined) {
      //             _this.$message({
      //               message: '服务器响应异常！',
      //               type: 'error'
      //             });
      //             return false;
      //           }
      //         });
      //       } else {
      //         // 判断是否是财务审批池
      //         if (role.indexOf('财务') > -1) {
      //           let deptRole = {
      //             deptId: ''
      //           };
      //           if (compId === 'STSBJ') {
      //             deptRole.deptId = 'BJ-CWB';
      //           }
      //           if (compId === 'STSGZ') {
      //             deptRole.deptId = 'GZ-CWB';
      //           }
      //           if (compId === 'STSNJ') {
      //             deptRole.deptId = 'NJ-CWB';
      //           }
      //           if (compId === 'STSSH') {
      //             deptRole.deptId = 'SH-CWB';
      //           }
      //           _this.$http.raw('/api/findUserRoles', deptRole).then(res => {
      //             let { code, datas } = res;
      //             // 判断Code状态
      //             if (code === 0) {
      //               let users = [];
      //               datas.map(item => {
      //                 if (item.roleName === role) {
      //                   users.push(item.userId);
      //                 }
      //               });

      //               let params = {
      //                 // 工单编号
      //                 flowCode: row.flowCode,
      //                 flowOriginator: _this.$store.state.userinfo.userId,

      //                 flowCurrentNode: nextNode,
      //                 flowCurrentUser: users.join(','),
      //                 // 工单优先级
      //                 flowPriority: row.flowPriority,
      //                 // 消息推送
      //                 msgPush: row.msgPush,
      //                 flowNode: row.flowCurrentNode,
      //                 status: 2,
      //                 result: '已发起',
      //                 note: '重新申请',
      //                 workResult: 1
      //               };
      //               _this.$http.raw('api/updateOrderStatus', params).then(res => {
      //                 let { code } = res;
      //                 // 判断Code状态
      //                 if (code === 0) {
      //                   _this.$message({
      //                     message: '发起流程成功！',
      //                     type: 'success'
      //                   });
      //                   _this.getmenusDataByPage();
      //                 }
      //               }).catch(err => {
      //                 if (err === undefined) {
      //                   _this.$message({
      //                     message: '服务器响应异常！',
      //                     type: 'error'
      //                   });
      //                   return false;
      //                 }
      //               });
      //             }
      //           }).catch(err => {
      //             if (err === undefined) {
      //               this.$message({
      //                 message: '服务器响应异常！',
      //                 type: 'error'
      //               });
      //               return false;
      //             }
      //           });
      //         } else if (role.indexOf('项目经理') > -1) {
      //           let rowDB = JSON.parse(row.formJson);
      //           let params = {
      //             // 工单编号
      //             flowCode: row.flowCode,
      //             flowOriginator: _this.$store.state.userinfo.userId,

      //             flowCurrentNode: nextNode,
      //             flowCurrentUser: rowDB.msgList.join(','),
      //             // 工单优先级
      //             flowPriority: row.flowPriority,
      //             // 消息推送
      //             msgPush: row.msgPush,
      //             flowNode: row.flowCurrentNode,
      //             status: 2,
      //             result: '已发起',
      //             note: '发起申请',
      //             workResult: 1
      //           };
      //           _this.$http.raw('api/updateOrderStatus', params).then(res => {
      //             let { code } = res;
      //             // 判断Code状态
      //             if (code === 0) {
      //               _this.$message({
      //                 message: '发起流程成功！',
      //                 type: 'success'
      //               });
      //               _this.getmenusDataByPage();
      //             }
      //           }).catch(err => {
      //             if (err === undefined) {
      //               _this.$message({
      //                 message: '服务器响应异常！',
      //                 type: 'error'
      //               });
      //               return false;
      //             }
      //           });
      //         } else {
      //           // 申请部门
      //           let deptRole = {
      //             deptId
      //           };
      //           _this.$http.raw('/api/findUserRoles', deptRole).then(res => {
      //             let { code, datas } = res;
      //             // 判断Code状态
      //             if (code === 0) {
      //               let users = [];
      //               datas.map(item => {
      //                 if (item.roleName === role) {
      //                   users.push(item.userId);
      //                 }
      //               });

      //               let params = {
      //                 // 工单编号
      //                 flowCode: row.flowCode,
      //                 flowOriginator: _this.$store.state.userinfo.userId,

      //                 flowCurrentNode: nextNode,
      //                 flowCurrentUser: users.join(','),
      //                 // 工单优先级
      //                 flowPriority: row.flowPriority,
      //                 // 消息推送
      //                 msgPush: row.msgPush,
      //                 flowNode: row.flowCurrentNode,
      //                 status: 2,
      //                 result: '已发起',
      //                 note: '重新申请',
      //                 workResult: 1
      //               };
      //               _this.$http.raw('api/updateOrderStatus', params).then(res => {
      //                 let { code } = res;
      //                 // 判断Code状态
      //                 if (code === 0) {
      //                   _this.$message({
      //                     message: '发起流程成功！',
      //                     type: 'success'
      //                   });
      //                   _this.getmenusDataByPage();
      //                 }
      //               }).catch(err => {
      //                 if (err === undefined) {
      //                   _this.$message({
      //                     message: '服务器响应异常！',
      //                     type: 'error'
      //                   });
      //                   return false;
      //                 }
      //               });
      //             }
      //           }).catch(err => {
      //             if (err === undefined) {
      //               this.$message({
      //                 message: '服务器响应异常！',
      //                 type: 'error'
      //               });
      //               return false;
      //             }
      //           });
      //         }
      //       }
      //     } else {
      //       let params = {
      //         // 工单编号
      //         flowCode: row.flowCode,
      //         flowOriginator: _this.$store.state.userinfo.userId,

      //         flowCurrentNode: nextNode,
      //         flowCurrentUser: user,
      //         // 工单优先级
      //         flowPriority: row.flowPriority,
      //         // 消息推送
      //         msgPush: row.msgPush,
      //         flowNode: row.flowCurrentNode,
      //         status: 2,
      //         result: '已发起',
      //         note: '重新申请',
      //         workResult: 1
      //       };
      //       _this.$http.raw('api/updateOrderStatus', params).then(res => {
      //         let { code } = res;
      //         // 判断Code状态
      //         if (code === 0) {
      //           _this.$message({
      //             message: '发起流程成功！',
      //             type: 'success'
      //           });
      //           _this.getmenusDataByPage();
      //         }
      //       }).catch(err => {
      //         if (err === undefined) {
      //           _this.$message({
      //             message: '服务器响应异常！',
      //             type: 'error'
      //           });
      //           return false;
      //         }
      //       });
      //     }
      //   }
      // }).catch(err => {
      //   if (err === undefined) {
      //     this.$message({
      //       message: '服务器响应异常！',
      //       type: 'error'
      //     });
      //     return false;
      //   }
      // });
    },

    // 取消申请
    cancel: function (row) {
      let _this = this;
      // 工单编号
      let flowCode = row.flowCode;
      // 能够取消申请的一定是申请人 - 登录人
      let logUser = _this.$store.state.userinfo.userId;

      // 收集请求参数
      let userResult = {
        orderCode: flowCode,
        userId: logUser
      };
      // 根据操作历史回溯发起人、发起节点
      _this.$http.raw('/api/findResults', userResult).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 发起节点
          let setUpNodeId = [];
          datas.map(item => {
            if (item.result === 1 && item.note === '发起申请') {
              setUpNodeId.push(item.flowNode);
            }
          });
          let params = {
            // 工单编号
            flowCode: flowCode,
            // 发起人
            flowOriginator: '',
            // 当前审批节点
            flowCurrentNode: setUpNodeId[0],
            // 当前审批人
            flowCurrentUser: logUser,
            // 工单状态
            status: 1,
            // 工单优先级
            // flowPriority: row.flowPriority,
            // 消息推送
            // msgPush: row.msgPush,
            // 处理结果
            result: '已取消',
            // 审批历史-审批节点
            flowNode: setUpNodeId[0],
            // 审批历史-审批意见
            note: '取消申请',
            // 审批历史-审批结果
            workResult: 4
          };
          this.$http.raw('api/updateOrderStatus', params).then(res => {
            let { code } = res;
            // 判断Code状态
            if (code === 0) {
              this.$message({
                message: '已取消申请！',
                type: 'success'
              });
              this.getmenusDataByPage();
            }
          }).catch(err => {
            if (err === undefined) {
              this.$message({
                message: '服务器响应异常！',
                type: 'error'
              });
              return false;
            }
          });
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 删除流程
    deleteLc: function (row) {
      let _this = this;
      let params = {
        id: row.id
      };
      _this.$http.post('/api/delWorkOrder', params).then(res => {
        let { code } = res;
        if (code === 0) {
          _this.getmenusDataByPage();
        }
      });
    },
    // 审批历史
    history: function (row) {
      let params = {
        flowCode: row.flowCode
      };
      this.$http.post('api/findWorkResultList', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          let currentNode = row.flowCurrentNode;
          let flowJson = JSON.parse(row.flowJson);
          flowJson.nodes.map(item => {
            if (item.id === currentNode) {
              item.color = '#FF0000';
            }
          });
          // 流程图预览
          this.modalVisible = true;
          this.nodeData = flowJson;
          this.historyLog = res.datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 显示编辑界面
    editHandle: function (row) {
      let params = {
        flowId: row.flowId
      };
      this.$http.post('api/findFlowRouter', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$router.push({
            path: res.datas,
            query: {
              node: 1,
              datas: row
            }
          });
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 表单数据
    formDatas: function (row) {
      let params = {
        flowId: row.flowId
      };
      this.$http.post('api/findFlowRouter', params).then(res => {
        let { code } = res;
        // 判断Code状态
        if (code === 0) {
          this.$router.push({
            path: res.datas,
            query: {
              node: 2,
              datas: row
            }
          });
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 显示新增界面
    addHandle: function () {
      // 弹出窗类型
      this.dialogStatus = 'create';
      // 弹出窗显示状态
      this.dialogFormVisible = true;
      // 重置新增界面默认数据
      this.editForm = {
        parentId: '0',
        compId: '',
        deptId: '',
        deptName: '',
        note: ''
      };
    },

    // 查询
    selHandle: function () {
      // 收集请求数据
      let params = {
        flowId: this.flowType,
        flowCode: this.formInline.flowCode,
        originatorTime: moment(this.formInline.flowOriginatorTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(this.formInline.flowOriginatorTime).format('YYYY-MM-DD'),
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      // 根据公司ID请求对应分页数据结果
      this.$http.raw('api/findOrderByFlowIdAndTime', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 刷新页面数据
    getmenusDataByPage () {
      // 收集请求参数
      let params = {
        flowId: this.flowType,
        flowCode: '',
        originatorTime: '',
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      this.$http.raw('api/findOrderByFlowIdAndTime', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    },

    // 查出当前申请人所在部门角色池领导
    getRoleList () {
      let _this = this;
      // 当前登录人信息
      let user = this.$store.state.userinfo;
      let deptRole = {
        deptId: user.deptId
      };
      _this.$http.raw('/api/findUserRoles', deptRole).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.rolesList = JSON.parse(JSON.stringify(datas));
        }
      });
    },
    // 发起申请时连续查询两个节点
    getNextNode (row, prevNode, flag) {
      let _this = this;
      // 初始数据源
      // let nodeDB = _this.$route.query.datas;
      let msgLists = JSON.parse(row.formJson).msgList;
      let firstParams = {
        flowId: _this.flowType,
        prevNode: prevNode
      };
      _this.firstNextRole = msgLists.join(',');
      return _this.$http.post('/api/findNextNode', firstParams).then(firstRes => {
        let { code } = firstRes;
        if (code === 0) {
          _this.rolesList.map(item => {
            if (item.roleName === firstRes.datas.flowNodeRole) {
              _this.firstNextRole = JSON.parse(JSON.stringify(item.userId)); // 下一节点审核人id
            }
          });
          let secondParams = {
            flowId: _this.flowType,
            prevNode: firstRes.datas.flowNodeId
          };
          return _this.$http.post('/api/findNextNode', secondParams).then(secondRes => {
            let { code } = secondRes;
            if (code === 0) {
              _this.rolesList.map(item => {
                if (item.roleName === secondRes.datas.flowNodeRole) {
                  _this.secondNextRole = JSON.parse(JSON.stringify(item.userId)); // 下下一节点审核人id
                }
              });
              if (flag === 2) { // 查询3步，不走项目经理节点
                let thirdParams = {
                  flowId: _this.flowType,
                  prevNode: secondRes.datas.flowNodeId
                };
                return _this.$http.post('/api/findNextNode', thirdParams).then(thirdRes => {
                  let { code } = thirdRes;
                  if (code === 0) {
                    _this.rolesList.map(item => {
                      if (item.roleName === thirdRes.datas.flowNodeRole) {
                        _this.thirdNextRole = JSON.parse(JSON.stringify(item.userId)); // 下下一节点审核人id
                      }
                    });
                    // 第一个和第二个人相同，继续往下找
                    if (_this.secondNextRole === _this.thirdNextRole) {
                      this.getNextNode(row, secondRes.datas.flowNodeId, 1);
                    } else { // 第一个人和第二个不同，将第一个人的值赋值
                      _this.globalParams = {
                        globalFlowCurrentNode: secondRes.datas.flowNodeId,
                        globallowCurrentUser: _this.secondNextRole
                      };
                      return _this.globalParams;
                    }
                  }
                });
              } else { // 查询2步，走项目经理节点
                // 第一个和第二个人相同，继续往下找
                if (_this.firstNextRole === _this.secondNextRole) {
                  this.getNextNode(row, firstRes.datas.flowNodeId, 1);
                } else { // 第一个人和第二个不同，将第一个人的值赋值
                  _this.globalParams = {
                    globalFlowCurrentNode: firstRes.datas.flowNodeId,
                    globallowCurrentUser: _this.firstNextRole
                  };
                  return _this.globalParams;
                }
              }
            }
          });
        }
      });
    }
  }
};
</script>

<style lang='scss'>
@import './index.scss';
</style>
